/*
 * @(#)MaintDmsRelationalWordAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.bean.DmsLocMaster;
import com.dcivision.dms.bean.DmsRelationalWord;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsLocMasterDAObject;
import com.dcivision.dms.dao.DmsRelationalWordDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
 * <p>Class Name:       MaintDmsRelationalWordAction.java    </p>
 * <p>Description:</p>
 * @author              weison liang
 * @company             DCIVision Limited
 * @creation date       03/09/2004
 * @version             $Revision: 1.36.2.3 $
 */

public class MaintDmsRelationalWordAction extends AbstractMaintAction{

  public static final String REVISION = "$Revision: 1.36.2.3 $";

  protected Integer countSuccess = new Integer(0);

  public void maintDmsRelationalWordAction(){

  }
   /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return ("com.dcivision.dms.dao.DmsRelationalWordDAObject");
  }
  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return (SystemFunctionConstant.DMS_ADMIN);
  }

  /**
   * setPageTitle
   * set the extend page title and page path.
   * default page path/title will be created by navmode and functionCode
   */
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping, ActionForward actionForward){
    String extendTitle = MessageResourcesFactory.getMessage(this.getSessionContainer(request).getSessionLocale(), "dms.relational.show_relational_word");
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE, extendTitle);
    request.setAttribute(GlobalConstant.EXTEND_PAGE_TITLE_SHOW_ONLY, new Boolean(true));
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
  	MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm)form;
	  String opMode = (relationalWordForm != null) ? relationalWordForm.getOpMode():request.getParameter("opMode");
	  String navMode = (relationalWordForm != null) ? relationalWordForm.getNavMode():request.getParameter("navMode");

	  if ("RETRIVE_RELATION_WORD".equals(opMode)) {
      // lee 06/12/19 EIP-1121 not found record, forward new
	    boolean isFound = this.findRecord(mapping,relationalWordForm,request,response);
      if (isFound) {
        relationalWordForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward("E");
      }else {
        relationalWordForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      }
	  }

    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.//
      //Update By Jim Zhou        2007/01/25      EIP-1417
      if (GlobalConstant.NAV_MODE_NEW.equals(relationalWordForm.getNavMode())){
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      }
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward != null) {
        return forward;
      }
      this.refreshFormData(mapping, relationalWordForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    }

	  if(opMode!=null&&"EXCEL_RELATION_WORD".equals(opMode)){
  	  return mapping.findForward("EX");
    }else if(opMode!=null&&"EXCEL_EXPORT".equals(opMode)){
    	this.relationalWordExcelExport(mapping,relationalWordForm,request);
 	    return mapping.findForward("EX");
    }else if(opMode!=null&&"EXCEL_IMPORT".equals(opMode)){
     	ArrayList resultList = this.relationalWordExcelImport(relationalWordForm,mapping,request);
      if ( ((resultList.get(0)).toString()).equals("Y") ) {
        addMessage(request, MESSAGE_RECORD_INSERT);
      }else{
       	this.addError(request, DmsErrorConstant.FILE_ERROR);
      }
      return mapping.findForward("EX");
    }
    return super.execute(mapping,relationalWordForm,request,response);
  }

  //insert the RelationalWord
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm) form;

    String opMode = relationalWordForm.getOpMode();
    DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);
    String sRealtionWord="";
    String sType="";
    String sRemove="";
    String sRelationWordID="";
    String relationKeyword=relationalWordForm.getRelationKeyword();
    TextUtility.stringValidation(relationKeyword);
    String sonKeyNumber = relationalWordForm.getKeyNumber();
    int intSonKeyNumber = TextUtility.parseInteger(sonKeyNumber);
    Integer intRelationWordID = null;
    DmsRelationalWord parentRealtionWord = (DmsRelationalWord)dmsRelationalWordDAO.getByKeyWord(relationKeyword);

    Integer parentID = null;
    if(parentRealtionWord!=null){
      parentID = parentRealtionWord.getID();
      throw new ApplicationException("dms.relational.word.set_up_duplicate");
    }else{
       DmsRelationalWord dmsRelationalWord=new DmsRelationalWord();
       Timestamp currTime = Utility.getCurrentTimestamp();
       dmsRelationalWord.setCreatorID(this.getSessionContainer(request).getUserRecordID());
       dmsRelationalWord.setCreateDate(currTime);
       dmsRelationalWord.setUpdaterID(this.getSessionContainer(request).getUserRecordID());
       dmsRelationalWord.setUpdateDate(currTime);
       dmsRelationalWord.setUpdateCount(new Integer(0));
       dmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(dmsRelationalWord.getCreatorID()));
       dmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(dmsRelationalWord.getUpdaterID()));
       dmsRelationalWord.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
       dmsRelationalWord.setWord(relationKeyword);
       dmsRelationalWord.setParentID(new Integer(0));
       dmsRelationalWord.setType("");
       DmsRelationalWord prd = (DmsRelationalWord)dmsRelationalWordDAO.insertObject(dmsRelationalWord);
       parentID = prd.getID();
     }


     for(int i=0;i<intSonKeyNumber;i++){
       sRealtionWord = request.getParameter("relationWord_"+i);
       TextUtility.stringValidation(sRealtionWord);
       try{
         sType=request.getParameter("bRelation_"+i);
         sRemove=request.getParameter("remove_"+i);
         sRelationWordID=request.getParameter("relationWordID_"+i);
         intRelationWordID = TextUtility.parseIntegerObj(sRelationWordID);
         Timestamp currTime = Utility.getCurrentTimestamp();
         String relationType = DmsRelationalWord.SINGLE_DIRECTION;
         if(sType!=null){
           relationType = DmsRelationalWord.BI_DIRECTION;
          }
          String relationRemove="";
          if(sRemove!=null){
            relationRemove=GlobalConstant.RECORD_STATUS_INACTIVE;
          }else{
            relationRemove=GlobalConstant.RECORD_STATUS_ACTIVE;
          }
          if(sRemove==null){
            if(Utility.isEmpty(sRelationWordID)||"null".equals(sRelationWordID )){
               DmsRelationalWord tmpDmsRelationalWord = new DmsRelationalWord();
               tmpDmsRelationalWord.setCreatorID(this.getSessionContainer(request).getUserRecordID());
               tmpDmsRelationalWord.setCreateDate(currTime);
               tmpDmsRelationalWord.setUpdaterID(this.getSessionContainer(request).getUserRecordID());
               tmpDmsRelationalWord.setUpdateDate(currTime);
               tmpDmsRelationalWord.setUpdateCount(new Integer(0));
               tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID()));
               tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID()));
               tmpDmsRelationalWord.setRecordStatus(relationRemove);
               tmpDmsRelationalWord.setWord(sRealtionWord);
               tmpDmsRelationalWord.setParentID(parentID);
               tmpDmsRelationalWord.setType(relationType);
               dmsRelationalWordDAO.insertObject(tmpDmsRelationalWord);
            }
          }
        }catch(Exception ee){
          log.error(ee, ee);
        }
     }
     this.selectRecord(mapping,relationalWordForm,request,response);
  }
  //update the RelationalWord
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm) form;
    String opMode = relationalWordForm.getOpMode();
    DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);
    DmsRelationalWord dmsRelationalWord=new DmsRelationalWord();
    String sRealtionWord="";
    String sType="";
    String sRemove="";
    String sRelationWordID="";
    String relationKeyword=relationalWordForm.getRelationKeyword();
    String sonKeyNumber = relationalWordForm.getKeyNumber();
    int intSonKeyNumber = TextUtility.parseInteger(sonKeyNumber);


    Integer intRelationWordID = null;//
    DmsRelationalWord parentRealtionWord = (DmsRelationalWord)dmsRelationalWordDAO.getByKeyWord(relationKeyword);
    Integer parentID = null;
    if(parentRealtionWord!=null){
      parentID = parentRealtionWord.getID();
    }else{

        Timestamp currTime = Utility.getCurrentTimestamp();
        dmsRelationalWord.setCreatorID(this.getSessionContainer(request).getUserRecordID());
        dmsRelationalWord.setCreateDate(currTime);
        dmsRelationalWord.setUpdaterID(this.getSessionContainer(request).getUserRecordID());
        dmsRelationalWord.setUpdateDate(currTime);
        dmsRelationalWord.setUpdateCount(new Integer(0));
        dmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(dmsRelationalWord.getCreatorID()));
        dmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(dmsRelationalWord.getUpdaterID()));
        dmsRelationalWord.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
        dmsRelationalWord.setWord(relationKeyword);
        dmsRelationalWord.setParentID(new Integer(0));
        dmsRelationalWord.setType("");
        DmsRelationalWord prd = (DmsRelationalWord)dmsRelationalWordDAO.insertObject(dmsRelationalWord);
        parentID = prd.getID();
     }
     for(int i=0;i<intSonKeyNumber;i++){
       try{
           sRealtionWord = request.getParameter("relationWord_"+i);
            sType=request.getParameter("bRelation_"+i);
            sRemove=request.getParameter("remove_"+i);
            sRelationWordID=request.getParameter("relationWordID_"+i);
            intRelationWordID = TextUtility.parseIntegerObj(sRelationWordID);
            Timestamp currTime = Utility.getCurrentTimestamp();
            String relationType = DmsRelationalWord.SINGLE_DIRECTION;
            if(sType!=null){
              relationType = DmsRelationalWord.BI_DIRECTION;
            }
            String relationRemove="";
            if(sRemove!=null){
              relationRemove=GlobalConstant.RECORD_STATUS_INACTIVE;
            }else{
              relationRemove=GlobalConstant.RECORD_STATUS_ACTIVE;
            }
           if(sRemove==null){
             if(!Utility.isEmpty(sRelationWordID)&&!"null".equals(sRelationWordID )){
                DmsRelationalWord tmpDmsRelationalWord = new DmsRelationalWord();
                tmpDmsRelationalWord = (DmsRelationalWord)dmsRelationalWordDAO.getObjectByID(intRelationWordID);
                tmpDmsRelationalWord.setWord(sRealtionWord);
                tmpDmsRelationalWord.setType(relationType);
                dmsRelationalWordDAO.updateObject(tmpDmsRelationalWord);

            }else{
              DmsRelationalWord tmpDmsRelationalWord = new DmsRelationalWord();
              tmpDmsRelationalWord.setCreatorID(sessionContainer.getUserRecordID());
              tmpDmsRelationalWord.setCreateDate(currTime);
              tmpDmsRelationalWord.setUpdaterID(sessionContainer.getUserRecordID());
              tmpDmsRelationalWord.setUpdateDate(currTime);
              tmpDmsRelationalWord.setUpdateCount(new Integer(0));
              tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID()));
              tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID()));
              tmpDmsRelationalWord.setRecordStatus(relationRemove);
              tmpDmsRelationalWord.setWord(sRealtionWord);
              tmpDmsRelationalWord.setParentID(parentID);
              tmpDmsRelationalWord.setType(relationType);
              dmsRelationalWordDAO.insertObject(tmpDmsRelationalWord);
          }
     }
     if(sRemove!=null && !Utility.isEmpty(sRelationWordID)&&!"null".equals(sRelationWordID )){
         DmsRelationalWord tmpDmsRelationalWord = new DmsRelationalWord();
         tmpDmsRelationalWord = (DmsRelationalWord)dmsRelationalWordDAO.getObjectByID(intRelationWordID);
         dmsRelationalWordDAO.deleteObject((tmpDmsRelationalWord));
     }
    }catch(Exception ee){
      log.error(ee, ee);
    }
  }
     //relationalWordForm.setSonKeywordList(null);
     this.selectRecord(mapping,relationalWordForm,request,response);
 }

  public ArrayList relationalWordExcelImport(ActionForm form, ActionMapping mapping, HttpServletRequest request) throws ApplicationException {
  	Connection conn = null;
    SessionContainer sessionContainer= null;
    ArrayList resultList = new ArrayList();
    MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm)form;
    FormFile uploadFile = relationalWordForm.getUploadFile();

    try {
      InputStream is = uploadFile.getInputStream();
      conn = this.getConnection(request);
      sessionContainer = this.getSessionContainer(request);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
      String keyWord = "";
      String type = "";

      Workbook workbook = Workbook.getWorkbook(is);
      int numOfSheets = workbook.getNumberOfSheets();
      for (int i = 0; i < numOfSheets; i++) {

        Sheet sheet = workbook.getSheet(i);
        for (int j = 1; j < sheet.getRows(); j++) {
          Cell[] cellAry = sheet.getRow(j);
          List rowList = new ArrayList();
          try {
            if (cellAry.length > 0 && TextUtility.noNull(cellAry[0].getContents()).trim().length() > 0) {
              rowList.add(TextUtility.noNull(cellAry[0].getContents()).trim());

              if (cellAry.length > 1 ) {
                if (!Utility.isEmpty(cellAry[1].getContents().trim())) {
                  rowList.add(TextUtility.noNull(cellAry[1].getContents()).trim());
                }

                if (cellAry.length > 2) {
                  if (DmsRelationalWord.BI_DIRECTION.equals(cellAry[2].getContents().trim()) || DmsRelationalWord.BI_DIRECTION.toLowerCase().equals(cellAry[2].getContents().trim())) {
                  	type = DmsRelationalWord.BI_DIRECTION;
                  }
                }else{
                  type = "S";
                }
              }

              processRow(rowList,type,request);
            }
          } catch (ApplicationException e) {

          }
        }
      }

      resultList.add(0, "Y");
      resultList.add(1, countSuccess);

      //conn.commit();
    } catch (Exception e) {
      log.error(e, e);

      resultList.add(0, "N");
      resultList.add(1, e.getMessage());

    }
    return resultList;
  }

  public void processRow(List rowList, String type, HttpServletRequest request) throws ApplicationException {
  	Connection conn = this.getConnection(request);
  	SessionContainer sessionContainer = this.getSessionContainer(request);

  	Integer parentID =null;
  	DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);

    for (int i = 0 ; i < rowList.size(); i++) {
  	  DmsRelationalWord parentRealtionWord = (DmsRelationalWord)dmsRelationalWordDAO.getByKeyWord((String)rowList.get(i));

  	  if(Utility.isEmpty(parentRealtionWord)){
  	    if(i==0){
  	      DmsRelationalWord dmsRelationalWord=new DmsRelationalWord();
          Timestamp currTime = Utility.getCurrentTimestamp();
          dmsRelationalWord.setCreatorID(this.getSessionContainer(request).getUserRecordID());
          dmsRelationalWord.setCreateDate(currTime);
          dmsRelationalWord.setUpdaterID(this.getSessionContainer(request).getUserRecordID());
          dmsRelationalWord.setUpdateDate(currTime);
          dmsRelationalWord.setUpdateCount(new Integer(0));
          dmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(dmsRelationalWord.getCreatorID()));
          dmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(dmsRelationalWord.getUpdaterID()));
          dmsRelationalWord.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
          dmsRelationalWord.setWord((String)rowList.get(0));
          dmsRelationalWord.setParentID(new Integer(0));
          dmsRelationalWord.setType("");
          DmsRelationalWord drw = (DmsRelationalWord)dmsRelationalWordDAO.insertObject(dmsRelationalWord);
          countSuccess = new Integer(countSuccess.intValue()+1);
          parentID = drw.getID();
  	    }else{
          String flag = "true";
          List tepList = dmsRelationalWordDAO.getListByRelationalWord((String)rowList.get(i),parentID);
          if (!Utility.isEmpty(tepList)){
            for (int k =0 ;k <tepList.size(); k++){
              DmsRelationalWord relationalWord = (DmsRelationalWord)tepList.get(k);
              if (relationalWord.getWord().equals(rowList.get(i))){
                flag = "false";
                break;
              }
            }
          }
          if("true".equals(flag)){
  		    DmsRelationalWord dmsRelationalWord=new DmsRelationalWord();
          Timestamp currTime = Utility.getCurrentTimestamp();
          dmsRelationalWord.setCreatorID(this.getSessionContainer(request).getUserRecordID());
          dmsRelationalWord.setCreateDate(currTime);
          dmsRelationalWord.setUpdaterID(this.getSessionContainer(request).getUserRecordID());
          dmsRelationalWord.setUpdateDate(currTime);
          dmsRelationalWord.setUpdateCount(new Integer(0));
          dmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(dmsRelationalWord.getCreatorID()));
          dmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(dmsRelationalWord.getUpdaterID()));
          dmsRelationalWord.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
          dmsRelationalWord.setWord((String)rowList.get(i));
          dmsRelationalWord.setParentID(parentID);
          dmsRelationalWord.setType(type);
          DmsRelationalWord drw = (DmsRelationalWord)dmsRelationalWordDAO.insertObject(dmsRelationalWord);
          countSuccess = new Integer(countSuccess.intValue()+1);
          }
  	    }
  	  }else{
  	    if(i==0){
  	      parentID = parentRealtionWord.getID();
  	    }else{
  	      parentID = parentRealtionWord.getParentID();
  	    }
  	  }
    }
    dmsRelationalWordDAO = null;
  }

  public void relationalWordExcelExport(ActionMapping mapping, ActionForm form, HttpServletRequest request) throws ApplicationException {
    Connection conn = null;
    SessionContainer sessionContainer= null;
    ArrayList resultList = new ArrayList();

    try {
      conn = this.getConnection(request);
      sessionContainer = this.getSessionContainer(request);
      //DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      //DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

      //DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);
      //resultList = (ArrayList)dmsRelationalWordDAO.getListAll();
      this.exportExclFolder(mapping,request);

    } catch (Exception e) {
      log.error(e, e);
    }
  }

  public void exportExclFolder(ActionMapping mapping, HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    ArrayList folderTreeList = this.getExportList(request);

    try {
      // creating excel file
      HSSFWorkbook wb = new HSSFWorkbook();
      HSSFSheet sheet = wb.createSheet("Export RelationalWord");
      sheet.setDefaultColumnWidth( (short) 24);
      short rowNum = 0;
      HSSFRow row = sheet.createRow(rowNum++);

      //creating the first rows
      createCell(wb, row, (short) 0, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.relational.show_keyword"));
      createCell(wb, row, (short) 1, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.relational.show_relational_word"));
      createCell(wb, row, (short) 2, MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.relational.show_type"));
      row = sheet.createRow(rowNum++);

      for(int j = 0; j < folderTreeList.size() ;j++){
        String keyword = "";
        String relationalWord = "";
      	String type = "";
        String[] exlWord= TextUtility.splitString((String)folderTreeList.get(j), "||");
        for(int i=0;i<exlWord.length;i++){
          if(i==0){
          	keyword = exlWord[i].toString();
          }else{
            String[] exlRelationalWord= TextUtility.splitString(exlWord[i], "/");
            if(exlRelationalWord.length>0) {
              relationalWord = exlRelationalWord[0];
            }
            if(exlRelationalWord.length>1) {
              type = exlRelationalWord[1];
            }
          }
          if(i!=0){
            createCell(wb, row, (short) 0, keyword);
            createCell(wb, row, (short) 1, relationalWord);
            createCell(wb, row, (short) 2, type);
            row = sheet.createRow(rowNum++);
          }
        }
      }

      ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
      wb.write(byteOut);

      DmsLocMasterDAObject locMasterDAO = new DmsLocMasterDAObject(sessionContainer, conn);
      DmsLocMaster locMaster = (DmsLocMaster) locMasterDAO.getObjectByID(new Integer(1));
      String locMasterPath = locMaster.getLocPath();

      long currentTime = new java.util.Date().getTime();
      byte[] excelData = byteOut.toByteArray();
      String path = locMasterPath+"/excel" + "_"+ currentTime+".xls";
      FileOutputStream f=new FileOutputStream(path);
      InputStream in = null;

      try {
        in = new ByteArrayInputStream(excelData);
        int c;
        while ( (c = in.read()) != -1) {
          f.write(c);
        }
      } catch (Exception e) {
        log.error(e);
      } finally {
        try {
          in.close();
        } catch (Exception ignore) {} finally {
          in = null;
        }
        try {
          f.close();
        } catch (Exception ignore) {} finally {
          f = null;
        }
      }
      request.getSession().setAttribute("exlExportFileName",path);
      byteOut.close();
      sessionContainer = null;
      locMasterDAO = null;



    }catch (Exception e) {
      log.error("export folder error.", e);
    }
  }

  private static void createCell(HSSFWorkbook wb, HSSFRow row, short column,String value) {
    HSSFCell cell = row.createCell(column);
    cell.setEncoding(cell.ENCODING_UTF_16);
    cell.setCellValue(value);
  }

  public ArrayList getExportList(HttpServletRequest request){
  	ArrayList resultList = new ArrayList();
  	String exportString ="";

  	SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
  	DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);

  	try{
      ArrayList keywordList = (ArrayList)dmsRelationalWordDAO.getRelationalWordListByParentID(new Integer(0));

  	  for(int i = 0; i < keywordList.size() ;i++){
  	    exportString = "";

        DmsRelationalWord dmsRelationalWord =(DmsRelationalWord)keywordList.get(i);
        exportString = exportString+dmsRelationalWord.getWord();
        ArrayList relationalWordList = (ArrayList)dmsRelationalWordDAO.getRelationalWordListByParentID(dmsRelationalWord.getID());

        for(int j = 0; j< relationalWordList.size(); j++){
          DmsRelationalWord dmsRelWord =(DmsRelationalWord)relationalWordList.get(j);
          exportString = exportString + "||" +dmsRelWord.getWord() + "/" + dmsRelWord.getType();
        }
        resultList.add(exportString);
  	  }
  	}catch(Exception e){
      log.error(e, e);
  	}
  	dmsRelationalWordDAO = null;
  	return resultList;
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    this.findRecord(mapping, form, request, response);
  }

  /**
   * Replace 'selectRecord' method with findRecord.
   * Return a boolean flag to show search result.
   * lee 06/12/19 EIP-1121
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ApplicationException
   */
  public boolean findRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
	  SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm) form;
    String opMode = relationalWordForm.getOpMode();
    DmsRelationalWordDAObject dmsRelationalWordDAO= new DmsRelationalWordDAObject(sessionContainer, conn);
    String relationKeyword = relationalWordForm.getRelationKeyword();

  	boolean foundKeyword = false;

    if(relationKeyword!=null){
    	//List relationalWordList = dmsRelationalWordDAO.getByRelationWordList(relationKeyword);
        List relationalWordList = dmsRelationalWordDAO.getWordListByKeyWord(relationKeyword);

      if(relationalWordList.size()>0){
        foundKeyword = true;
      	relationalWordForm.setSonKeywordList(relationalWordList);
      }else if("RETRIVE_RELATION_WORD".equals(opMode) && relationalWordList.size()<=0 ){
        addMessage(request, "common.list.no_record_found");
      }
    }
    relationalWordForm.setCurFunctionCode(this.getFunctionCode());
    return foundKeyword;
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsRelationalWordForm relationalWordForm = (MaintDmsRelationalWordForm) form;
    String sRealtionWord="";
    String sType="";
    String sRelationWordID="";
    String relationKeyword=relationalWordForm.getRelationKeyword();
    String sonKeyNumber = relationalWordForm.getKeyNumber();
    int intSonKeyNumber = TextUtility.parseInteger(sonKeyNumber);
    Integer intRelationWordID = null;
    List result = new ArrayList();
     for(int i=0;i<intSonKeyNumber;i++){
       try{
       	 sRelationWordID=request.getParameter("relationWordID_"+i);
         sRealtionWord = request.getParameter("relationWord_"+i);
         sType=request.getParameter("bRelation_"+i);
         String relationType = DmsRelationalWord.SINGLE_DIRECTION;
         if(sType!=null){
           relationType = DmsRelationalWord.BI_DIRECTION;
          }
               DmsRelationalWord tmpDmsRelationalWord = new DmsRelationalWord();
               sRealtionWord = sRealtionWord == null ?"":sRealtionWord;
               tmpDmsRelationalWord.setID(TextUtility.parseIntegerObj(sRelationWordID));
               tmpDmsRelationalWord.setWord(sRealtionWord);
               tmpDmsRelationalWord.setType(relationType);
               result.add(tmpDmsRelationalWord);
        }catch(Exception ee){
          log.error(ee, ee);
        }
     }
     relationalWordForm.setCurFunctionCode(this.getFunctionCode());
     relationalWordForm.setSonKeywordList(result);
  }
}
